const app = getApp();

Page({
  data: {
    status: 'all',
    leaveList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false
  },

  onLoad: function() {
    this.fetchLeaveList();
  },

  onShow: function() {
    // 页面显示时刷新数据
    if (this.data.needRefresh) {
      this.setData({
        page: 1,
        leaveList: [],
        hasMore: true,
        needRefresh: false
      });
      this.fetchLeaveList();
    }
  },

  onPullDownRefresh: function() {
    this.setData({
      page: 1,
      leaveList: [],
      hasMore: true
    });
    
    this.fetchLeaveList().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 获取请假列表
  fetchLeaveList: function() {
    if (this.data.isLoading) return Promise.resolve();
    
    this.setData({ isLoading: true });
    
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.serverUrl}/api/admin/leaves`,
        method: 'GET',
        data: {
          status: this.data.status === 'all' ? '' : this.data.status,
          page: this.data.page,
          pageSize: this.data.pageSize
        },
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // 处理状态文本
            const list = res.data.list.map(item => {
              let statusText = '';
              let statusClass = '';
              
              switch(item.status) {
                case 'pending':
                  statusText = '待审批';
                  statusClass = 'pending';
                  break;
                case 'approved':
                  statusText = '已批准';
                  statusClass = 'approved';
                  break;
                case 'rejected':
                  statusText = '已拒绝';
                  statusClass = 'rejected';
                  break;
              }
              
              return {
                ...item,
                statusText,
                status: statusClass
              };
            });
            
            const newList = this.data.page === 1 ? list : [...this.data.leaveList, ...list];
            
            this.setData({
              leaveList: newList,
              hasMore: list.length === this.data.pageSize,
              page: this.data.page + 1
            });
            
            resolve();
          } else {
            wx.showToast({
              title: res.data.message || '获取请假列表失败',
              icon: 'none'
            });
            reject();
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
          reject(err);
        },
        complete: () => {
          this.setData({ isLoading: false });
        }
      });
    });
  },

  // 切换状态标签
  switchTab: function(e) {
    const status = e.currentTarget.dataset.status;
    if (status === this.data.status) return;
    
    this.setData({
      status,
      page: 1,
      leaveList: [],
      hasMore: true
    });
    
    this.fetchLeaveList();
  },

  // 加载更多
  loadMore: function() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.fetchLeaveList();
    }
  },

  // 查看请假详情
  viewLeaveDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/admin/leave/detail/detail?id=${id}`
    });
  },

  // 批准请假
  approveLeave: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认批准',
      content: '确定批准该请假申请吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateLeaveStatus(id, 'approved');
        }
      }
    });
  },

  // 拒绝请假
  rejectLeave: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '拒绝原因',
      editable: true,
      placeholderText: '请输入拒绝原因',
      success: (res) => {
        if (res.confirm && res.content) {
          this.updateLeaveStatus(id, 'rejected', res.content);
        }
      }
    });
},

  // 更新请假状态
  updateLeaveStatus: function(id, status, reason = '') {
    wx.showLoading({
      title: '处理中...'
    });
    
    wx.request({
      url: `${app.globalData.serverUrl}/api/admin/leaves/${id}/status`,
      method: 'PUT',
      data: {
        status,
        reason
      },
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          wx.showToast({
            title: status === 'approved' ? '已批准' : '已拒绝',
            icon: 'success'
          });
          
          // 刷新列表
          this.setData({
            page: 1,
            leaveList: [],
            hasMore: true
          });
          this.fetchLeaveList();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },
  
  // 导出请假数据
  exportLeaveData: function() {
    // 显示导出选项
    wx.showActionSheet({
      itemList: ['导出当前筛选结果', '导出本周请假', '导出本月请假', '导出全部请假'],
      success: (res) => {
        const index = res.tapIndex;
        let status = '';
        let startDate = '';
        let endDate = '';
        
        if (index === 0) {
          // 导出当前筛选结果
          status = this.data.status === 'all' ? '' : this.data.status;
          this.doExportLeave({ status });
        } else if (index === 1) {
          // 导出本周请假
          const today = new Date();
          const dayOfWeek = today.getDay() || 7; // 获取星期几，星期日为0转为7
          const startDay = new Date(today);
          startDay.setDate(today.getDate() - dayOfWeek + 1); // 计算本周一
          
          const endDay = new Date(today);
          endDay.setDate(today.getDate() + (7 - dayOfWeek)); // 计算本周日
          
          startDate = this.formatDate(startDay);
          endDate = this.formatDate(endDay);
          
          this.doExportLeave({ startDate, endDate });
        } else if (index === 2) {
          // 导出本月请假
          const today = new Date();
          const year = today.getFullYear();
          const month = today.getMonth();
          
          const startDay = new Date(year, month, 1);
          const endDay = new Date(year, month + 1, 0);
          
          startDate = this.formatDate(startDay);
          endDate = this.formatDate(endDay);
          
          this.doExportLeave({ startDate, endDate });
        } else if (index === 3) {
          // 导出全部请假
          this.doExportLeave({});
        }
      }
    });
  },
  
  // 执行导出操作
  doExportLeave: function(params) {
    wx.showLoading({
      title: '准备导出...',
    });
    
    // 构建下载链接
    let downloadUrl = `${app.globalData.serverUrl}/api/admin/leaves/export`;
    
    // 添加查询参数
    const queryParams = [];
    if (params.status) {
      queryParams.push(`status=${params.status}`);
    }
    if (params.startDate) {
      queryParams.push(`startDate=${params.startDate}`);
    }
    if (params.endDate) {
      queryParams.push(`endDate=${params.endDate}`);
    }
    
    if (queryParams.length > 0) {
      downloadUrl += '?' + queryParams.join('&');
    }
    
    console.log('导出URL:', downloadUrl);
    
    // 使用小程序的下载文件API
    wx.downloadFile({
      url: downloadUrl,
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        console.log('导出响应:', res);
        
        if (res.statusCode === 200) {
          // 显示导出成功的提示
          wx.showToast({
            title: '导出成功',
            icon: 'success',
            duration: 1500
          });
          
          // 打开文件
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: 'xlsx',
            success: function() {
              console.log('打开文档成功');
            },
            fail: function(error) {
              console.error('打开文档失败:', error);
              // 如果打开失败，提供保存选项
              wx.showModal({
                title: '无法自动打开文件',
                content: '文件已下载，是否保存到本地？',
                confirmText: '保存',
                success(modalRes) {
                  if (modalRes.confirm) {
                    wx.saveFile({
                      tempFilePath: res.tempFilePath,
                      success(saveRes) {
                        wx.showToast({
                          title: '文件已保存',
                          icon: 'success'
                        });
                        console.log('保存成功，路径:', saveRes.savedFilePath);
                      },
                      fail(saveErr) {
                        console.error('保存失败:', saveErr);
                        wx.showToast({
                          title: '保存失败',
                          icon: 'none'
                        });
                      }
                    });
                  }
                }
              });
            }
          });
        } else {
          wx.showModal({
            title: '导出失败',
            content: '服务器返回错误，请稍后重试',
            showCancel: false
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('下载文件失败:', err);
        
        // 显示更详细的错误信息
        wx.showModal({
          title: '导出失败',
          content: '网络错误或服务器无响应，请检查网络连接后重试',
          showCancel: false
        });
      }
    });
  },
  
  // 日期格式化函数
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
});